import type { RouteRecordRaw } from 'vue-router'
import type { IBreadCrumb } from '@/base-ui/breadcrumb/types'

let firstMenu: any = null

/***
 * 根据角色下的菜单获取routes
 * @params userMenus 所有的菜单信息
 * @returns routes 符合当前菜单的routes
 */
export function mapMenusToRoutes(userMenus: any[]): RouteRecordRaw[] {
  const routes: RouteRecordRaw[] = []

  // 1. 获取目录下所有定义好的routes
  const allRoutes: RouteRecordRaw[] = []

  const routeFiles = require.context('@/router/main', true, /\.ts/)
  routeFiles.keys().forEach((key) => {
    const route = require('@/router/main' + key.split('.')[1])
    allRoutes.push(route.default)
  })

  // 2. 取出符合当前菜单的routes
  const _recurseGetRoute = (menus: any[]) => {
    for (const menu of menus) {
      if (menu.type === 2) {
        const route = allRoutes.find((route) => route.path === menu.url)
        if (route) {
          routes.push(route)
        }
        if (!firstMenu) {
          firstMenu = menu
        }
      } else {
        _recurseGetRoute(menu.children)
      }
    }
  }

  _recurseGetRoute(userMenus)

  return routes
}

/**
 * 根据当前url映射的menu
 * @param userMenus 所有的菜单信息
 * @param currentPath 当前url
 * @returns findMenu 映射的menu结果
 */
export function mapPathToMenu(userMenus: any[], currentPath: string, breadCrumbData?: IBreadCrumb[]): any {
  for (const menu of userMenus) {
    if (menu.type === 1) {
      const findMenu = mapPathToMenu(menu.children ?? [], currentPath)
      if (findMenu) {
        breadCrumbData?.push({ name: menu.name })
        breadCrumbData?.push({ name: findMenu.name, path: findMenu.url })
        return findMenu
      }
    } else if (menu.type === 2 && menu.url === currentPath) {
      return menu
    }
  }
}

/**
 * 根据当前选中的菜单而显示的面包屑
 * @param userMenus
 * @param currentPath
 * @returns breadCrumbData 面包屑的数据
 */
export function mapPathToBreadCrumb(userMenus: any[], currentPath: string): IBreadCrumb[] {
  const breadCrumbData: IBreadCrumb[] = []
  mapPathToMenu(userMenus, currentPath, breadCrumbData)
  return breadCrumbData
}

/**
 * 获取用户操作权限
 * @param userMenus
 * @returns permissions 当前角色下的菜单中的所有权限
 */
export function mapMenuToPermission(userMenus: any[]) {
  const permissions: string[] = []

  const _recurseGetPermission = (menus: any) => {
    for (const menu of menus) {
      if (menu.type === 1 || menu.type === 2) {
        _recurseGetPermission(menu.children ?? [])
      } else if (menu.type === 3) {
        permissions.push(menu.permission)
      }
    }
  }
  _recurseGetPermission(userMenus)

  return permissions
}

/**
 * 获取菜单树的拥有权限的叶子节点
 * @param menuList
 * @returns leafKeys 菜单树的拥有权限的叶子节点
 */
export function mapMenuToLeafKes(menuList: any[]) {
  const leafKeys: number[] = []

  const _recurseGetLeafKeys = (menus: any[]) => {
    for (const menu of menus) {
      if (menu.children) {
        _recurseGetLeafKeys(menu.children)
      } else {
        leafKeys.push(menu.id)
      }
    }
  }
  _recurseGetLeafKeys(menuList)

  return leafKeys
}

export { firstMenu }
